<?php 
/**
 * 用户验证处理类
 * 
 * @author chengtao
 * @package User 
 */
class UserCheck extends Think{
	/**
	 * 用户登录验证
	 * @param $password 密码
	 * @return $flag 布尔值
	 */
	public function login(){
		$flag = 0;
		$username = trim($_POST['username']);
		$password = trim($_POST['password']);
		if(empty($username) || empty($password)){
			return array('flag'=>FALSE,'msg'=>'email或者密码不能为空');
		}
		$where = "username='{$username}'";
		$where .=' AND password="'.md5($password).'"';
		$group_name = strtolower(GROUP_NAME);
		if($group_name == 'home'){
			$where .= " AND (auth=1 OR auth=0)";
		}elseif($group_name == 'manager'){
			$where .= " AND auth=2";
		}
		
		$User = M('user');
		$user_info = $User->where($where)->find();
		if(empty($user_info)) return array('flag'=>FALSE,'msg'=>'用户名不存在或密码错误');
		if($user_info['state'] == 0){
			return array('flag'=>FALSE,'msg'=>'您的用户已经被禁用请联系主管或管理员');
		}
		$this->setLogin($user_info);
		return array('flag'=>TRUE,'msg'=>'登录成功');
	}
	/**
	 * 用户退出登录
	 * 后台使用manager作为cookie的认证key
	 */
	public function logout(){
		$key = C('USER_LOGIN_KEY');
		$uid = C('USER_LOGIN_UID');
		Cookie::delete($key);
		Cookie::delete($uid);

	}
	/**
	 * 设置用户为登录状态
	 */
	private  function setLogin($user_info){
		//记录用户登录日志
		$UserLog = M('userlog');
		$data['uid'] = $user_info['uid'];
		$data['time'] = $_SERVER['REQUEST_TIME'];
		$data['ip'] = get_client_ip();
		$UserLog->add($data);
		$key = C('USER_LOGIN_KEY');
		$uid = C('USER_LOGIN_UID');
		if(Session::get('keep_login') == 'on'){
			$expire = 0;
		}else{
			$expire = C('LGOIN_COOKIE_EXPIRE');
		}
		Cookie::set($key,$user_info['uid'].$user_info['password'].$_SERVER['HTTP_USER_AGENT'].C('LOGIN_COOKIE_KEY'),$expire);
		Cookie::set($uid,$user_info['uid'],$expire);
	}
	/**
	 * 延长用户登录cookie有效期
	 */
	private function extendLogin(){
		if(Session::get('keep_login') != 'on')return;
		$key = C('USER_LOGIN_KEY');
		$uid = C('USER_LOGIN_UID');
		Cookie::set($key,Cookie::get($key),C('LGOIN_COOKIE_EXPIRE'));
		Cookie::set($uid,Cookie::get($uid),C('LGOIN_COOKIE_EXPIRE'));
	}
	/**
	 * 检测用户是否是登录状态
	 */
	public function checkUserLogin(){
		$User = M('user');
		$uid = Cookie::get(C('USER_LOGIN_UID'));
		if($uid){
			$user_info = $User->where("uid = {$uid}")->find();
			if($user_info['uid'].$user_info['password'].$_SERVER['HTTP_USER_AGENT'].C('LOGIN_COOKIE_KEY') == Cookie::get(C('USER_LOGIN_KEY'))){
				Session::set('uid',			$user_info['uid']);
				Session::set('email',		$user_info['email']);
				Session::set('username',	$user_info['username']);
				Session::set('auth',		$user_info['auth']);
				$this->extendLogin();
			}else{
				Session::destroy();
			}
		}else{
			Session::destroy();
		}
	}
}
?>